const { app, BrowserWindow, ipcMain, dialog } = require('electron')
const DataStore = require('./MusicDataStore')

console.log(app.getPath('userData'))

const myStore = new DataStore({ name: 'MusicData' })
class AppWindow extends BrowserWindow {
  constructor(config, fileLocation) {
    const baseicConfig = {
      width: 800,
      height: 600,
      webPreferences: {
        nodeIntegration: true
      }
    }
    const finnalConfig = { ...baseicConfig, ...config }
    super(finnalConfig)

    this.loadFile(fileLocation)

    this.once('ready-to-show', () => {
      this.show()
    })
  }
}

app.on('ready', () => {
  const mainWindow = new AppWindow({}, './renderer/index.html')
  mainWindow.webContents.on('did-finish-load', () => {
    console.log('page did finish load')
    mainWindow.send('getTracks', myStore.getTracks())
  })

  let addWindow
  ipcMain.on('add-music-window', () => {
    addWindow = new AppWindow(
      {
        width: 500,
        height: 400,
        parent: mainWindow
      },
      './renderer/add.html'
    )
  })

  ipcMain.on('add-tracks', (event, tracks) => {
    const updatedTracks = myStore.addTracks(tracks).getTracks()
    mainWindow.send('getTracks', updatedTracks)
  })

  ipcMain.on('close-add-window', (event) => {
    console.log(addWindow)
    addWindow.close()
  })

  ipcMain.on('delete-tracks', (event, id) => {
    const updatedTracks = myStore.deleteTracks(id).getTracks()
    mainWindow.send('getTracks', updatedTracks)
  })

  ipcMain.on('open-music-file', event => {
    dialog.showOpenDialog(
      {
        properties: ['openFile', 'multiSelections'],
        filters: [{ name: 'Music', extensions: ['mp3'] }]
      },
      files => {
        event.sender.send('selected-file', files)
      }
    )
  })
})
